package com.dc.pay.factory;

import com.dc.pay.strategy.IPayStrategy;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: KEYD
 * @Date: 2020/1/12 12:32
 * @Desc: 工厂  初始化不同的策略行为
 */
public class StrategyFactory {

    private static Map<String, IPayStrategy> strategyBean = new ConcurrentHashMap<>(); //容器 自己管理，做成单例

    public static IPayStrategy getPayStartegy(String classAddress) {
        try {
            if (StringUtils.isEmpty(classAddress)) {
                return null;
            }
            IPayStrategy beanPayStrategy = strategyBean.get(classAddress);
            if (beanPayStrategy != null) {
                return beanPayStrategy;
            }
            //1、使用Java的反射初始化子类
            Class<?> forName = Class.forName(classAddress);
            //2、Java的反射机制初始化对象
            IPayStrategy payStategy = (IPayStrategy) forName.newInstance();
            strategyBean.put(classAddress, payStategy);
            return payStategy;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
